package com.lw.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lw.yygh.enums.AuthStatusEnum;
import com.lw.yygh.exception.YyghException;
import com.lw.yygh.helper.JwtHelper;
import com.lw.yygh.model.user.Patient;
import com.lw.yygh.result.ResultCodeEnum;
import com.lw.yygh.model.user.UserInfo;
import com.lw.yygh.user.mapper.UserInfoMapper;
import com.lw.yygh.user.service.PatientService;
import com.lw.yygh.user.service.UserInfoService;
import com.lw.yygh.vo.user.LoginVo;
import com.lw.yygh.vo.user.UserAuthVo;
import com.lw.yygh.vo.user.UserInfoQueryVo;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PatientService patientService;

    //用户登录
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //获取手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断手机号和验证码是否为空
        if (StringUtils.isEmpty( phone )||StringUtils.isEmpty( code )){
            throw new YyghException( ResultCodeEnum.PARAM_ERROR );
        }
        //判断手机验证码和输入的验证码是否一致
        String redisCode= (String) redisTemplate.opsForValue().get( phone );
        if (!code.equals( redisCode )){
            throw new YyghException( ResultCodeEnum.PARAM_ERROR );
        }
        UserInfo userInfo = null;
        //判断是否微信绑定手机号
        if(!StringUtils.isEmpty(loginVo.getOpenid())) {
            UserInfo user=baseMapper.selectOne( new QueryWrapper<UserInfo>().eq( "phone", phone ) );
            if (user!=null){
                //如果该手机号已经绑定微信或者已经注册，抛出异常
                throw new YyghException( ResultCodeEnum.REGISTER_MOBLE_ERROR );
            }
            //否则绑定该手机号
            userInfo = baseMapper.selectOne( new QueryWrapper<UserInfo>().eq( "openid", loginVo.getOpenid()) );
            if(null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }
        //判断是否第一次登录，根据手机号查询数据库，如果不存在就是第一次登陆
        if (userInfo==null){
            userInfo  = baseMapper.selectOne( new QueryWrapper<UserInfo>().eq( "phone", phone ) );
            if (userInfo==null){
                //第一次登录 直接注册
                userInfo=new UserInfo();
                userInfo.setName( "" );
                userInfo.setPhone( phone );
                userInfo.setAuthStatus( 0 );
                baseMapper.insert( userInfo );
                userInfo.setStatus( 1 );
                baseMapper.update( userInfo,new QueryWrapper<UserInfo>().eq( "phone", phone ) );
            }
        }
        //检验是否禁用
        if(userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }
        //不是第一次，直接登录
        //返回登录信息
        //返回登录用户名
        //返回token信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //jwt生成token字符串
        String token = JwtHelper.createToken( userInfo.getId(), name );
        map.put("token", token);

        return map;
    }

    //用户认证
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        //根据用户id查询用户
        UserInfo userInfo = baseMapper.selectById( userId );
        //设置认证信息
        userInfo.setName( userAuthVo.getName() );
        userInfo.setCertificatesNo( userAuthVo.getCertificatesNo() );
        userInfo.setCertificatesType( userAuthVo.getCertificatesType() );
        userInfo.setCertificatesUrl( userAuthVo.getCertificatesUrl() );
        userInfo.setAuthStatus( AuthStatusEnum.AUTH_RUN.getStatus());//认证中
        //进行信息更新
        baseMapper.updateById( userInfo );
    }

    //用户列表（条件带分页）
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //获取条件值
        String name = userInfoQueryVo.getKeyword();//用户状态
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();//认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间
        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty( name )){
            wrapper.like( "name",name );
        }
        if (!StringUtils.isEmpty( status )){
            wrapper.like( "status",status );
        }
        if (!StringUtils.isEmpty( authStatus )){
            wrapper.like( "auth_status",authStatus );
        }
        if (!StringUtils.isEmpty( createTimeBegin )){
            wrapper.ge( "create_time",createTimeBegin );
        }
        if (!StringUtils.isEmpty( createTimeEnd )){
            wrapper.le( "create_time",createTimeEnd );
        }
        //调用mapper实现条件查询
        Page<UserInfo> selectPage = baseMapper.selectPage( pageParam, wrapper );
        //编号变成对应的值
        selectPage.getRecords().stream().forEach( item->{
            this.packageUserInfo(item);
        } );
        return selectPage;
    }

    //用户锁定
    @Override
    public void lock(long userId, Integer status) {
        if (status==0||status==1){
            UserInfo userInfo=baseMapper.selectById( userId );
            userInfo.setStatus( status );
            baseMapper.updateById( userInfo );
        }
    }

    //用户详情(包括就诊人信息)
    //用户详情
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String,Object> map = new HashMap<>();
        //根据userid查询用户信息
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        map.put("userInfo",userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientService.findAllByUserId(userId);
        map.put("patientList",patientList);
        return map;
    }

    //认证审批  2通过  -1不通过
    @Override
    public void approval(long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }



    private UserInfo  packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        String authStatusString="";
        if (userInfo.getAuthStatus()==1){
            authStatusString="认证中";
        }else if (userInfo.getAuthStatus()==2){
            authStatusString="已认证";
        }else {
            authStatusString="未认证";
        }
        userInfo.getParam().put("authStatusString",authStatusString);
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
